package file;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;

public class FileServerThread extends Thread {
	  
	public static void receiveFile(File file, Socket socket2) {
		
		PrintWriter pWriterSocket;
		try {
            
            if (file.getName() != null && !file.getName().equals("")) {
                    
                            
               pWriterSocket = new PrintWriter(new OutputStreamWriter(socket2.getOutputStream()), true);
               pWriterSocket.println(file.getName());
                    
	           System.out.println("Fichier demander : " + file.getName());
	        }
	    }
	    catch (Exception e) {
	            
	            System.out.println("Probleme dans receiveFile : " + e.getMessage());
	    }	
		
		// TODO Auto-generated method stub
		byte[] b = new byte[1024];
	    int len = 0;
	    int bytcount = 1024;
	    FileOutputStream inFile;
		try {
			inFile = new FileOutputStream(file);
		    InputStream is = socket2.getInputStream();
		    BufferedInputStream in2 = new BufferedInputStream(is, 1024);
		    while ((len = in2.read(b, 0, 1024)) != -1) {
		      bytcount = bytcount + 1024;
		      inFile.write(b, 0, len);
		    }
		    System.out.println("Bytes Writen : " + bytcount);

		    // Sending the response back to the client.
		    ObjectOutputStream oos = new ObjectOutputStream(socket2.getOutputStream());
		    oos.flush();
		    oos.writeObject("COMPLETETRANSFERT");
		    System.out.println("Message sent to the client is " + "COMPLETETRANSFERT");

		    in2.close();
		    inFile.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	}